package com.wxsh.test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HanlpTokenize2 {
	public static void main(String[] args) {
		// 请求头中的token
		String token = "2145fa74hf61jf9a8vj417a9341123sd";
		// 申请的接口地址
		String url = "https://www.hanlp.com/api/segment/chinese";
		// 所有参数
		String text = "HanLP是GitHub上最成功的NLP项目，全球数百万NLP开发者的共同选择！";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("text", text);
		// 执行api
		String result = doHanlpApi(token, url, params);
		System.out.println(result);
	}

	public static String doHanlpApi(String token, String url, Map<String, Object> params) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 添加header请求头，token请放在header里
			httpPost.setHeader("token", token);
			// 创建参数列表
			List<NameValuePair> paramList = new ArrayList<NameValuePair>();
			if (params != null) {
				for (String key : params.keySet()) {
					// 所有参数依次放在paramList中
					paramList.add(new BasicNameValuePair(key, (String) params.get(key)));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
				httpPost.setEntity(entity);
			}
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
			return resultString;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}